package com.ruoyi.project.manage.project.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.ProjectConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.manage.approveLog.domain.ApproveLog;
import com.ruoyi.project.manage.approveLog.service.IApproveLogService;
import com.ruoyi.project.manage.detail.domain.ProjectInvestDetail;
import com.ruoyi.project.manage.detail.service.IProjectInvestDetailService;
import com.ruoyi.project.manage.project.domain.ProjectExport;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.manage.project.domain.Project;
import com.ruoyi.project.manage.project.service.IProjectService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 项目信息Controller
 * 
 * @author fangkun
 * @date 2022-03-28
 */
@Controller
@RequestMapping("/manage/project")
public class ProjectController extends BaseController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectController.class);

    private String prefix = "manage/project";

    @Autowired
    private IProjectService projectService;
    @Autowired
    private IApproveLogService approveLogService;
    @Autowired
    private IProjectInvestDetailService investDetailService;

    @RequiresPermissions("manage:project:view")
    @GetMapping()
    public String project()
    {
        return prefix + "/project";
    }

    @GetMapping("/database")
    public String projectDatabase()
    {
        return prefix + "/projectDatabase";
    }

    @PostMapping("/database")
    @ResponseBody
    public TableDataInfo database(Project project)
    {
        startPage();
        List<Project> list = projectService.selectProjectList(project);
        return getDataTable(list);
    }

    @GetMapping("/recycle")
    public String projectRecycle()
    {
        return prefix + "/projectRecycle";
    }

    @PostMapping("/recycle")
    @ResponseBody
    public TableDataInfo recycle(Project project)
    {
        startPage();
        List<Project> list = projectService.selectDelProjectList(project);
        return getDataTable(list);
    }

    /**
     * 查询项目信息列表
     */
    @RequiresPermissions("manage:project:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Project project)
    {
        startPage();
        // 设置当前登录人查看本人录入的项目信息
        project.setCreateBy(ShiroUtils.getLoginName());
        List<Project> list = projectService.selectProjectList(project);
        return getDataTable(list);
    }

    /**
     * 导出项目列表
     */
    @Log(title = "项目列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Project project)
    {
        // 设置当前登录人查看本人录入的项目信息
        project.setCreateBy(ShiroUtils.getLoginName());
        List<Project> list = projectService.selectProjectList(project);
        List<ProjectExport> projectExports = domain2Export(list);
        ExcelUtil<ProjectExport> util = new ExcelUtil<ProjectExport>(ProjectExport.class);
        return util.exportExcel(projectExports, "项目数据");
    }

    /**
     * 导出项目列表
     */
    @Log(title = "项目列表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportIds")
    @ResponseBody
    public AjaxResult exportIds(String ids)
    {
        List<Project> list = projectService.selectProjectListByIds(ids);
        List<ProjectExport> projectExports = domain2Export(list);
        ExcelUtil<ProjectExport> util = new ExcelUtil<ProjectExport>(ProjectExport.class);
        return util.exportExcel(projectExports, "项目数据");
    }

    /**
     * 导出项目库列表
     */
    @Log(title = "项目库", businessType = BusinessType.EXPORT)
    @PostMapping("/database/export")
    @ResponseBody
    public AjaxResult databaseExport(Project project)
    {
        List<Project> list = projectService.selectProjectList(project);
        List<ProjectExport> projectExports = domain2Export(list);
        ExcelUtil<ProjectExport> util = new ExcelUtil<ProjectExport>(ProjectExport.class);
        return util.exportExcel(projectExports, "项目库数据");
    }

    public ProjectExport domain2Export(Project project){
        if(project==null) return null;
        ProjectExport projectExport = new ProjectExport();
        BeanUtils.copyProperties(project,projectExport);

        return projectExport;
    }

    public List<ProjectExport> domain2Export(List<Project> projectList){
        if(projectList==null || projectList.isEmpty()) return null;

        List<ProjectExport> projectExports = new ArrayList<>();
        for(Project dto : projectList){
            projectExports.add(domain2Export(dto));
        }
        return projectExports;
    }

    /**
     * 新增项目信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存项目信息
     */
    @RequiresPermissions("manage:project:add")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Project project)
    {
        return success(projectService.insertProject(project));
    }

    /**
     * 修改项目信息
     */
    @RequiresPermissions("manage:project:edit")
    @GetMapping("/edit/{projectId}")
    public String edit(@PathVariable("projectId") Long projectId, ModelMap mmap)
    {
        Project project = projectService.selectProjectByProjectId(projectId);
        mmap.put("project", project);
        return prefix + "/edit";
    }

    /**
     * 修改保存项目信息
     */
    @RequiresPermissions("manage:project:edit")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Project project)
    {
        return toAjax(projectService.updateProject(project));
    }

    /**
     * 修改项目基本信息
     */
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editBasic")
    @ResponseBody
    public AjaxResult editBasic(Project project)
    {
        return toAjax(projectService.editBasic(project));
    }

    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editOther")
    @ResponseBody
    public AjaxResult editOther(Project project)
    {
        return toAjax(projectService.editOther(project));
    }
    /**
     * 修改项目信息
     */
    @RequiresPermissions("manage:project:edit")
    @GetMapping("/detail/{projectId}")
    public String detail(@PathVariable("projectId") Long projectId, ModelMap mmap, String source)
    {
        Project project = projectService.selectProjectByProjectId(projectId);
        mmap.put("project", project);
        // 获取当前年
        String currentYear = DateUtils.dateTimeNow("yyyy");
        mmap.put("currentYear", currentYear);
        // 项目投资情况统计
        List<Map> investStat = investDetailService.statProjectInvest(projectId);
        if (investStat.size() == 0) {
            Map defaultMap = new HashMap<>();
            defaultMap.put("year", currentYear);
            defaultMap.put("doneInvest", 0);
            investStat.add(defaultMap);
        }
        mmap.put("investStat", investStat);
        // 项目投资明细
        ProjectInvestDetail detailParam = new ProjectInvestDetail();
        detailParam.setProjectId(projectId);
        detailParam.setYear(Integer.valueOf(currentYear));
        List<ProjectInvestDetail> projectInvestDetails = investDetailService.selectProjectInvestDetailList(detailParam);

        if (projectInvestDetails == null || projectInvestDetails.size() == 0) {
            projectInvestDetails = new ArrayList<>();
            for (int i = 1; i <= 12; i++) {
                ProjectInvestDetail detail = new ProjectInvestDetail();
                detail.setYear(Integer.valueOf(currentYear));
                detail.setMonth(i);
                detail.setProjectId(projectId);
                projectInvestDetails.add(detail);
            }
        }

        mmap.put("projectInvestDetails", projectInvestDetails);
        // 获取流转信息
        ApproveLog param = new ApproveLog();
        param.setEntityId(projectId);
        param.setEntityType(ProjectConstants.APPROVAL_TYPE_PROJECT);
        List<ApproveLog> approveLogs = approveLogService.selectApproveLogList(param);
        mmap.put("approveLogs", approveLogs);

        mmap.put("source", source);
        return prefix + "/detail";
    }

    /**
     * 提交项目信息
     */
    @RequiresPermissions("manage:project:submit")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/submit")
    @ResponseBody
    public AjaxResult submit(int projectId)
    {
        return toAjax(projectService.submitProject(projectId));
    }

    /**
     * 撤回项目
     */
    @RequiresPermissions("manage:project:withdraw")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/withdraw")
    @ResponseBody
    public AjaxResult withdraw(int projectId)
    {
        return toAjax(projectService.withdraw(projectId));
    }

    /**
     * 删除项目信息
     */
//    @RequiresPermissions("manage:project:remove")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(projectService.deleteProjectByProjectIds(ids));
    }

    /**
     * 复原项目信息
     */
    @Log(title = "项目信息", businessType = BusinessType.OTHER)
    @PostMapping( "/restore")
    @ResponseBody
    public AjaxResult restore(String ids)
    {
        return toAjax(projectService.restoreProjectByProjectIds(ids));
    }

    /**
     * 地图
     */
    @GetMapping("/map")
    public String map()
    {
        return prefix + "/map";
    }

    @GetMapping("/changeInfo/{projectId}/{type}")
    public String detail(@PathVariable("projectId") Long projectId, @PathVariable("type") String type, ModelMap mmap)
    {
        Project project = projectService.selectProjectByProjectId(projectId);
        mmap.put("project", project);

        mmap.put("type", type);

        if (StringUtils.equals(type, "basic")) {
            return prefix + "/changeBasic";
        }
        return prefix + "/change";
    }
}
